04 / 13

Can an Interface have fields? Why or why not?

Difficulty: 2/10

Fields in Interfaces

The answer is language-specific. In Java, interface fields are implicitly public, static and final, so they represent constants rather than per-object mutable state. Java interfaces cannot define ordinary instance fields. In C#, interfaces traditionally did not contain instance fields either; newer language features have expanded what interfaces can express, but they still are not a mechanism for storing ordinary per-instance object state. If an abstraction needs mutable instance state, an abstract class or composition is generally more appropriate.

javascript
  1. 1

    Java interface fields are implicitly public, static and final.

  2. 2

    They are constants, not per-object mutable state.

  3. 3

    Interfaces are primarily contracts rather than state containers.

  4. 4

    C# interface capabilities differ by language version, but interfaces are not intended as ordinary instance-state holders.

  5. 5

    Use a class or abstract class when shared instance state is part of the abstraction.

Follow-up Questions

  • Why are Java interface fields static final?
  • Can interfaces contain methods with implementation?
  • Should constants be placed in interfaces?
  • How does C# differ from Java regarding interface members?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.